from django.shortcuts import render
from rest_framework import viewsets, mixins, response

from servers.models import Server, NetworkDevice, IP
from servers.serializers import ServerSerializer, NetworkDeviceSerializer, IPSerializer, ServerAutoReportSerializer
from servers.filter import ServerFilter
from rest_framework.permissions import AllowAny


class ServerViewset(viewsets.ReadOnlyModelViewSet, mixins.UpdateModelMixin, mixins.DestroyModelMixin):

    """
    list: 返回服务器列表
    retrieve: 返回单个服务器信息
    update: 更新服务器归属
    destroy: 删除服务器记录
    """
    serializer_class = ServerSerializer
    queryset = Server.objects.all()
    filter_class = ServerFilter
    # filter_fields = ('hostname', 'idc', 'cabinet', "service", "server_purpose", "server_type")
    filter_fields = ('hostname', 'idc', 'cabinet', 'business_parent', 'business_line')
    # extra_perm_map = {  # 为get方法添加权限验证utils.permissions重写了类
    #     "GET": ['servers.view_server']
    # }

    def get_queryset(self):
        queryset = super(ServerViewset, self).get_queryset()
        queryset = queryset.order_by("id")
        return queryset


class ServerAutoReportViewset(viewsets.GenericViewSet, mixins.CreateModelMixin):
    """
    create: 创建服务器记录
    """
    serializer_class = ServerAutoReportSerializer
    queryset = Server.objects.all()
    permission_classes = (AllowAny,)


class NetworkDeviceViewset(viewsets.ReadOnlyModelViewSet):
    """
    list: 返回网卡设备列表
    retrieve: 返回单个网卡设备信息
    """
    serializer_class = NetworkDeviceSerializer
    queryset = NetworkDevice.objects.all()


class IPViewset(viewsets.ReadOnlyModelViewSet):
    """
    list: 返回IP列表
    retrieve: 返回单个IP信息
    """
    serializer_class = IPSerializer
    queryset = IP.objects.all()
